﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using SARS.Biz;
using SARS.Entity;

namespace SARS.Course.Group
{
    public partial class AssignStudentGroup : Page
    {
        private readonly GroupBO groupBiz = new GroupBO();
        private readonly UserBO userBiz = new UserBO();
        private GroupEntity group;
        private int groupId;

        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Cache.SetNoStore();
            if (!string.IsNullOrEmpty(Request.QueryString["gid"]))
            {
                groupId = Int32.Parse(Request.QueryString["gid"]);
                group = groupBiz.RetrieveGroupById(groupId);
                group.GroupTutorial = userBiz.RetrieveTutorsByGroupId(groupId);
                lblCourseName.Text = group.Course.CourseName;
                lblGroupName.Text = group.GroupName;
                lblTutorsName.Text = group.GroupTutorialNames;

                if (!IsPostBack)
                {
                    Session["CHECKED_ITEMS"] = null;
                    BindStudentGridViewData();
                }
            }
        }

        protected void btnAssing_OnClick(object sender, EventArgs e)
        {
            SaveCheckedValues();
            var checkedStudent = (List<string>) Session["CHECKED_ITEMS"];
            var coordinator = (CoordinatorEntity) userBiz.RetrieveUserByUserName(Page.User.Identity.Name);
            groupBiz.AssignStudentsIntoGroup(groupId, coordinator.UserID, checkedStudent);

            Response.Redirect("StudentGroupDetail.aspx?gid=" + groupId);
        }

        protected void gvStudentList_OnPageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            SaveCheckedValues();
            gvStudentList.PageIndex = e.NewPageIndex;
            BindStudentGridViewData();
            PopulateCheckedValues();
        }

        protected void btnCancel_OnClick(object sender, EventArgs e)
        {
            Response.Redirect("SelectGroupToAssign.aspx");
        }

        private void BindStudentGridViewData()
        {
            List<StudentEntity> list = userBiz.GetAllCourseStudentOutOfGroup(groupId, group.CourseID);
            gvStudentList.DataSource = list;
            gvStudentList.DataBind();

            if (list.Count == 0)
            {
                btnAssing.Visible = false;
            }
        }

        //This method is used to populate the saved checkbox values
        private void PopulateCheckedValues()
        {
            var checkedStudent = (List<string>) Session["CHECKED_ITEMS"];
            if (checkedStudent != null && checkedStudent.Count > 0)
            {
                foreach (GridViewRow gvrow in gvStudentList.Rows)
                {
                    string index = gvStudentList.DataKeys[gvrow.RowIndex].Value.ToString();
                    if (checkedStudent.Contains(index))
                    {
                        var myCheckBox = (CheckBox) gvrow.FindControl("cbSelect");
                        myCheckBox.Checked = true;
                    }
                }
            }
        }

        //This method is used to save the checkedstate of values
        private void SaveCheckedValues()
        {
            var checkedIds = new List<string>();

            foreach (GridViewRow gvrow in gvStudentList.Rows)
            {
                string index = gvStudentList.DataKeys[gvrow.RowIndex].Value.ToString();
                bool result = ((CheckBox) gvrow.FindControl("cbSelect")).Checked;

                // Check in the Session
                if (Session["CHECKED_ITEMS"] != null)
                {
                    checkedIds = (List<string>) Session["CHECKED_ITEMS"];
                }
                if (result)
                {
                    if (!checkedIds.Contains(index))
                    {
                        checkedIds.Add(index);
                    }
                }
                else
                {
                    checkedIds.Remove(index);
                }
            }
            if (checkedIds != null && checkedIds.Count > 0)
            {
                Session["CHECKED_ITEMS"] = checkedIds;
            }
        }
    }
}